package io.github.xbeeant.eoffice.service.impl;

import io.github.xbeeant.core.ApiResponse;
import io.github.xbeeant.core.IdWorker;
import io.github.xbeeant.eoffice.config.AbstractSecurityMybatisPageHelperServiceImpl;
import io.github.xbeeant.eoffice.mapper.DocTemplateCatMapper;
import io.github.xbeeant.eoffice.mapper.DocTemplateMapper;
import io.github.xbeeant.eoffice.model.DocTemplate;
import io.github.xbeeant.eoffice.model.DocTemplateCat;
import io.github.xbeeant.eoffice.rest.vo.DocTemplateCatVo;
import io.github.xbeeant.eoffice.service.IDocTemplateCatService;
import io.github.xbeeant.spring.mybatis.pagehelper.IMybatisPageHelperDao;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 模板分组
 */
@Service
public class DocTemplateCatServiceImpl extends AbstractSecurityMybatisPageHelperServiceImpl<DocTemplateCat, Long> implements IDocTemplateCatService {

    @Autowired
    private DocTemplateCatMapper docTemplateCatMapper;

    @Autowired
    private DocTemplateMapper docTemplateMapper;

    @Override
    public List<DocTemplateCat> cats(String userId) {
        DocTemplateCat example = new DocTemplateCat();
        example.setCreateBy(userId);
        ApiResponse<List<DocTemplateCat>> listRst = selectAllByExample(example);

        return listRst.getData();
    }

    @Override
    public List<DocTemplateCatVo> fetch(Integer type, String userId) {
        DocTemplateCat example = new DocTemplateCat();
        example.setType(type);
        List<DocTemplateCatVo> list = docTemplateCatMapper.all(type, userId);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<Long> cids = new ArrayList<>(list.size());
        for (DocTemplateCat docTemplateCat : list) {
            cids.add(docTemplateCat.getCid());
        }
        List<DocTemplate> docTemplates = docTemplateMapper.fetch(cids);
        for (DocTemplateCatVo docTemplateCatVo : list) {
            for (DocTemplate docTemplate : docTemplates) {
                if (docTemplateCatVo.getCid().equals(docTemplate.getCid())) {
                    docTemplateCatVo.addTemplate(docTemplate);
                }
            }
        }
        return list;
    }

    @Override
    public IMybatisPageHelperDao<DocTemplateCat, Long> getRepositoryDao() {
        return this.docTemplateCatMapper;
    }

    @Override
    public void setDefaults(DocTemplateCat record) {
        if (record.getCid() == null) {
            record.setCid(IdWorker.getId());
        }
    }
}
